$(document).ready(function() {
	
	Invitesq.PhotoSlideModel = Invitesq.PhotoModel.extend({
		defaults : _.extend (Invitesq.PhotoModel.prototype.defaults, {
			"caption" : "",
			"index": ""
		})
	});
	
	
	// Flexslider template 
	Invitesq.flexPhotoSliderTemplate = function() {
		return '' +
		'<ul class="slides">' +
		'</ul>' 
		;
	};
	
	Invitesq.flexPhotoTemplate = function() {
		return '' +
			'<img id="<%= id %>" src="<%= src %>" />'
	      //'<a href="<%= link %>"><img src="<%= src %>" /></a>' +
		  //'<p class="flex-caption"><%= caption %></p>' +
	    ;
	}
	
	// Template for slider upload 
	Invitesq.uploadSliderTemplate = function() {
		return '' +
		'<div class="row-fluid">' +
			'<div class="span12" id="drop-area-slider">' + 
				'<div class="span3"></div>' +
				'<div class="span6 dropbox">' +
					'<img src="/assets/img/DropBox.png"/>' + 
				'</div>' +
				'<div class="span3 buttons">' +
					'<button class="btn" id="browse">Browse</button>' +
				'</div>' +
			'</div>' +
		'</div>'
		;
	};
	
	// Template for slider thumbnail
	Invitesq.slideThumbnailCollectionTemplate = function() {
		return '' +
		'<h3 style="margin:10px;">All thumbnails</h3>'+
		'<div class="span3 buttons">' +
			'<button class="btn btn-primary" id="upload">Save</button>'  +
			'<button class="btn btn-success" id="slide">Slide</button>' +
		'</div>' 
		;
	};
	
	Invitesq.slideThumbTemplate = function() {
		return '' +
			'<div class="remove-btn" title="Remove this photo" id="<%= id %>"/>' +
			'<img src="<%=  src %>"/>' +
			'<div class="progress">' +
				'<div class="bar" style="width: <%=progress%>%;"></div>' +
			'</div>' 
			; 
	};

	// For individual view: thumbnail + progress slider
	// Bind to a model
	// It simply refreshes when model is changed
	Invitesq.FlexThumbnailView =  Backbone.View.extend({
		tagName : "div",
		className : "thumbnail span2",
		
		template : _.template(Invitesq.slideThumbTemplate()),
		
		initialize : function() {
			_.bindAll(this, 'render');
			this.model.on("change", this.render, this);
		},
		
		render: function() {
			$(this.el).html(this.template(this.model.toJSON()));
			return this;
		}		
	});
	
	// Flexslider collection 
	Invitesq.FlexPhotoCollection = Backbone.Collection.extend({
		model: Invitesq.PhotoModel
	});
	Invitesq.flexCollection = new Invitesq.FlexPhotoCollection();
	
	// Flexslider views
	// Single photo view 
	Invitesq.FlexPhotoView = Backbone.View.extend({
		
		tagName: 'li',
		
		template: _.template(Invitesq.flexPhotoTemplate()),
		
		initialize: function() {
			_.bindAll(this,"render");
			this.model.on("change", this.render, this);
			
		},
		
		render: function() {
			$(this.el).html(this.template(this.model.toJSON()));
			return this;
		}		
	});
	// Photo collection view
	Invitesq.FlexPhotoCollectionView = Backbone.View.extend({
		
		tagName: 'div',
		
		id: "thumbnails",
		
		template: _.template(Invitesq.slideThumbnailCollectionTemplate()),
		
		collection: Invitesq.flexCollection,
		
		initialize: function() {
			_.bindAll(this,"render","addPhoto");
			this.collection.on("add", this.addPhoto, this);
			this.collection.on("remove", this.removePhoto, this);
		},
		
		// Render the collection
		render: function() {
			console.log("render collection");
			var $this = this;
			$(this.el).html(this.template({}));
			
			// Add photo into this collection
			this.collection.each(function(photo) {
				console.log("add photo " + photo);
				$this.addPhoto(photo);
			});
			return this;
		},
		
		// Add one photo
		addPhoto: function(model) {
			var thumbnailView = new Invitesq.FlexThumbnailView({model: model});
			$(this.el).append(thumbnailView.render().el);
		},	
		// Remove photo
		removePhoto: function(model) {
			console.log("remove photo " + model.id);
			$("#"+model.id).parent().remove();
		}	
	});
	
	// Photo slider view - slider is another view of collection
	Invitesq.FlexPhotoSliderView = Invitesq.FlexPhotoCollectionView.extend({
		
		id: 'flexSlider',
		
		className: 'flexslider',
		
		template: _.template(Invitesq.flexPhotoSliderTemplate()),
		
		_super: Invitesq.FlexPhotoCollectionView.prototype,
		
		initialize: function() {
			_.bindAll(this,"render","addPhoto","removePhoto");
			this.collection.on("add", this.addPhoto, this);
			this.collection.on("remove", this.removePhoto, this);
		},
		
		sliderOptions: {
			directionNav:false,
			slideshow: true,
			slideshowSpeed: 4000,           //Integer: Set the speed of the slideshow cycling, in milliseconds
			animationDuration: 500,         //Integer: Set the speed of animations, in milliseconds
			start: function(slider) {
			  console.log("Slider count" + slider.count);
			}
		},
		
		
		// Render 
		render: function(){
			// Inherit the super inituploader function
			this._super.render.apply(this);		
			console.log("render slider");
			// Activate flex slider
			$(this.el).flexslider(this.sliderOptions);
			return this;
		},
		// Add photo
		addPhoto: function(model) {
			var flexPhotoView = new Invitesq.FlexPhotoView({model: model});
			this.$(".slides").append(flexPhotoView.render().el);
		},	
		
		// Remove photo
		removePhoto: function(model) {
			console.log("remove photo " + model.id);
			$("#"+model.id).parent().replaceWith('');
		}	
		
		
	});
	
	// Main upload slider view 
	Invitesq.UploadSliderView = Backbone.View.extend({
		
		tagMame : "div",
		
		className : "",
		
		id: 'upload-slider-view',
		
		dropAreaId: 'drop-area-slider', 
		
		template: _.template(Invitesq.uploadSliderTemplate()),
		
		sliderAlbumId: -1,
		
		sliderEnable: false,
		
		collection: Invitesq.flexCollection,
		
		removeImages: [],
		
		dropAreaCss_in : {'background-color' : '#F7F7F7'},
		
		dropAreaCss_out : {'background-color' : '#EEEEEE'},
		
		//_super: Invitesq.UploadAlbumView.prototype,
		// Inherit super's event and add own event 
		/*events: function(){
	      return _.extend({},this._super.events,{
	          
	      });
	     	
	     
	  	},*/
		
		events: {
			"drop #drop-area-slider" : "dropHandler",
			"dragover #drop-area-slider" : "dragEnterHandler",
			"dragleave #drop-area-slider" : "dragLeaveHandler",
			"click #upload" : "uploadHandler",
			"click #slide" : "slideHandler",
			"click .remove-btn" : "removeHandler"
		},
		
		initialize : function() {
			_.bindAll(this, 'render', 'dropHandler', 'uploadHandler', 'uploadToCoverAlbum', 'dragEnterHandler', 'dragLeaveHandler','removeHandler');
			// Bind change event of collection to trigger slider re-render
			//this.collection.on("add", this.refreshSlider, this);
			this.thumbnailsView = new Invitesq.FlexPhotoCollectionView();
			this.dropArea = ("#" + this.dropAreaId);
		}, 
		

		initUploader: function() {
			// Init the upload options
			this.uploaderOptions = {
				runtimes : 'html5',
				browse_button : 'browse',
				container : this.id,
				max_file_size : '10mb',
				drop_element : this.dropAreaId,

				filters : [{
					title : "Image files",
					extensions : "jpg,gif,png,jpeg"
				}]
			};
			
			this.uploader = new plupload.Uploader(this.uploaderOptions);
			// For AppEngine. the URL is dynamic, hence we need to
			// overwrite the settings before the file is uploaded
			this.uploader.bind('UploadFile', function(up, file) {
				console.log('[UploadFile]', file);
				$.ajax({
					url : '/api/photo/get-upload-url/',
					async : false,
					success : function(data) {
						up.settings.url = data;
						console.log(up.settings.url);

					},
				});
			});

			this.uploader.init();

			// When file is uploaded, change progress of model. This will propagate
			// to the corresponding view
			this.uploader.bind('UploadProgress', function(up, file) {
				var photo = Invitesq.flexCollection.get(file.id);
				photo.set({
					progress : file.percent
				});
				console.log(photo);
			});
			var $this = this;
			//
			this.uploader.bind('FilesAdded', function(up, files) {
				$.each(files, function(i, file) {
					console.log("FileAdded");

					// Create new photoModel and add to collection
					var photoSlideModel = new Invitesq.PhotoSlideModel();
					$this.collection.add(photoSlideModel);

					// Set attributes
					photoSlideModel.set({
						id : file.id,
						index : i
					});

					// Read file and parse result to src
					var reader = new FileReader();
					reader.onload = function(e) {
						photoSlideModel.set({
							src : e.target.result,
						});
					}

					reader.readAsDataURL(file.nativeFile);
				});

				up.refresh();

				// Reposition Flash/Silverlight
			});

			// Handle error
			this.uploader.bind('Error', function(up, err) {
				console.log("Error: " + err.code + ", Message: " + err.message + (err.file.id ? ", File: " + err.file.name : ""));
				// If file extension is wrong, remove photo model from collection
				if (err.code == -601) {
					console.log("Wrong extension. Remove photo with id:" + err.file.id);
					var photo = this.collection.get(err.file.id);
					this.collection.remove(photo);
				}
				up.refresh();
				// Reposition Flash/Silverlight
			});
			
			// File uploaded
			this.uploader.bind('UploadComplete', function(up) {
				console.log('Upload done');
				// Remove existing images if necessary
				$.post('/api/photo/delete-list/', {
					'photos' : $this.removeImages
				}, function(result) {
					console.log("Deleted photo successfully " + result);
					$this.$("#thumbnails").slideUp();
					$this.slideHandler();
				});
			});
		},

	
		uploadHandler : function(e) {
			// Get the slider album if existed
			this.uploadToCoverAlbum();
			e.preventDefault();
		},
		
		
		slideHandler : function(){
			this.sliderEnable = true;
			this.sliderView = VM.reuseView("flexSliderView", function() {
				return new Invitesq.FlexPhotoSliderView();
			});
			$(this.dropArea).empty().html(this.sliderView.render().el);
		},
		
		removeHandler : function(e){
			var $this = this;
			var currentId  = e.target.id;
			
			// Remove from collection ui
			var photo = this.collection.get(currentId);
			this.collection.remove(photo);
			
			// Remove from uploader file list
			var file = this.uploader.getFile(currentId);
			this.uploader.removeFile(file);
	        
	        // If file exists in uploader -> new upload
	        if (!file) {
	        	this.removeImages.push (currentId);
	        	console.log("List of remove images" + this.removeImages);
	        }
	        // Refresh slider
			console.log("Remove image with id " + e.target.id + "Length" + this.collection.length);
			if (this.sliderEnable==true){
				this.slideHandler();
			}
		},
		
		render: function() {
			$(this.el).html(this.template({}));
			$(this.el).append(this.thumbnailsView.render().el);
			this.$('#thumbnails').slideDown('slow');
			return this;
		},

		dropHandler : function(e) {
			$this = this;
			console.log("Files are dropped in drop area");
			
			$(this.dropArea).css(this.dropAreaCss_out);
			
			if (this.sliderEnable==true){
				this.slideHandler();
			}
		},
			
		dragEnterHandler : function() {
			console.log("File is dragged into browser");
			$(this.dropArea).css(this.dropAreaCss_in);
			return false;
		},
		
		dragLeaveHandler : function() {
			console.log("File is dragged out of browser");
			$(this.dropArea).css(this.dropAreaCss_out);
			return false;
		},
		
		uploadToCoverAlbum : function(album) {
			console.log("upload to album " + Invitesq.eventCoverId + " of event: " + Invitesq.eventId);
			// Upload to cover album
			this.uploader.settings.multipart_params = {
				"album_id": Invitesq.eventCoverId,
				"event_id": Invitesq.eventId
			};
			this.uploader.start();
			
		}

	});
	
	
});